<script setup>
  import {
    onMounted,
    ref,
    watch,
    onBeforeUnmount,
    defineProps,
    nextTick,
    computed
  } from 'vue'
  import * as echarts from 'echarts'
  import { Promotion, Sunset, Sunrise } from '@element-plus/icons-vue'
  import solarLunar from 'solarlunar'
  import weatherIcon from '@/composables/weatherIcon'

  // 接收数据
  const props = defineProps({
    detailWeather: {
      type: Object,
      default: () => ({})
    },
    hourWeather: {
      type: Array,
      default: () => []
    },
    weekWeather: {
      type: Array,
      default: () => []
    }
  })

  // 农历日期
  const dateInfo = ref({
    gregorianDate: '',
    weekDay: '',
    lunarDate: ''
  })
  const currentHour = ref(new Date().getHours())
  const currentTime = ref('')

  onMounted(() => {
    const now = new Date()
    const year = now.getFullYear()
    const month = now.getMonth() + 1
    const day = now.getDate()

    // 更新时间显示
    setInterval(() => {
      const date = new Date()
      currentTime.value = `${date.getHours().toString().padStart(2, '0')}:${date
        .getMinutes()
        .toString()
        .padStart(2, '0')}`
    }, 1000)

    dateInfo.value.gregorianDate = `${month.toString().padStart(2, '0')}月${day
      .toString()
      .padStart(2, '0')}日`
    const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
    dateInfo.value.weekDay = weekDays[now.getDay()]
    try {
      const lunar = solarLunar.solar2lunar(year, month, day)
      dateInfo.value.lunarDate = `农历${lunar.monthCn}${lunar.dayCn}`
        .replace('月', '')
        .replace('初', '月初')
    } catch (e) {
      dateInfo.value.lunarDate = '农历日期获取失败'
    }
  })

  // 24小时天气图表
  const activeName = ref('temperature')
  const chartRef = ref(null)
  const chartRef2 = ref(null)
  let myChart = null
  let myChart2 = null
  let timer = null

  // 生成当前时间开始的7小时数据
  const getCurrentHoursData = () => {
    const startIndex = currentHour.value
    return Array.from({ length: 7 }, (_, i) => {
      const index = (startIndex + i) % 24
      return props.hourWeather[index]
    })
  }

  // 时间轴标签生成
  const generateTimeLabels = () => {
    return Array.from({ length: 7 }, (_, i) => {
      const hour = (currentHour.value + i) % 24
      return i === 0 ? '现在' : `${hour.toString().padStart(2, '0')}:00`
    })
  }

  // 图表配置
  const chartData = ref({
    temperature: {
      title: '24小时温度变化趋势',
      yAxisName: '温度(°C)',
      min: 10,
      max: 40,
      formatter: '{value}°C'
    },
    wind: {
      title: '24小时风力变化趋势',
      yAxisName: '风力(级)',
      min: 0,
      max: 5,
      formatter: '{value}级'
    },
    airQuality: {
      title: '24小时空气质量变化',
      yAxisName: 'AQI指数',
      min: 0,
      max: 100,
      formatter: '{value}'
    }
  })

  // 初始化图表
  const initChart = () => {
    if (!myChart) return

    const currentData = chartData.value[activeName.value]
    const displayData = getCurrentHoursData()

    const option = {
      title: {
        text: currentData.title,
        left: 'left',
        top: 0,
        textStyle: {
          color: '#333',
          fontSize: 20,
          fontWeight: 'bold'
        }
      },
      xAxis: {
        type: 'category',
        data: generateTimeLabels()
      },
      yAxis: {
        type: 'value',
        name: currentData.yAxisName,
        min: currentData.min,
        max: currentData.max,
        axisLabel: {
          formatter: currentData.formatter
        }
      },
      series: [
        {
          data: displayData
            .filter(d => d)
            .map(d => {
              const value = d?.[
                activeName.value === 'temperature'
                  ? 'temp'
                  : activeName.value === 'wind'
                    ? 'windScale'
                    : 'aqi'
                ]
              return value !== undefined ? value : null
            })
            .filter(val => val !== null),
          type: 'line',
          smooth: true,
          lineStyle: {
            color: '#409EFF',
            width: 3
          },
          itemStyle: {
            color: '#409EFF'
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: 'rgba(64, 158, 255, 0.5)' },
              { offset: 1, color: 'rgba(64, 158, 255, 0.1)' }
            ])
          }
        }
      ],
      grid: {
        left: '3%',
        right: '3%',
        bottom: '3%',
        top: '23%',
        containLabel: true
      }
    }

    myChart.setOption(option, true)
  }

  // 周天气图表数据拼接
  // 空气质和天气图标量颜色映射
  const aqColorMap = {
    优: '#82c91e', // 保持清新的绿色
    良: '#f0bc00', // 保持温和的黄色
    中: '#ff7f00', // 更标准的橙色
    差: '#e74c3c' // 深红色，更醒目但不刺眼
  }
  // 星期映射
  const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
  // 处理数据
  const weekWeatherList = computed(() => {
    return props.weekWeather.map(item => {
      // 解析日期
      const [month, day] = item.forecastDate.split('/').map(Number)
      const currentYear = new Date().getFullYear()
      const date = new Date(currentYear, month - 1, day)
      const weekday = weekdays[date.getDay()]

      return {
        ...item,
        aqColor: aqColorMap[item.aq] || 'gray',
        ...weatherIcon[item.weatherCode],
        weekday // 新增星期字段
      }
    })
  })

  // 周天气预报图表
  const initWeeklyChart = () => {
    const option = {
      xAxis: {
        type: 'category',
        show: false,
        data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
      },
      yAxis: {
        type: 'value',
        splitLine: { show: false },
        axisLabel: {
          show: false,
          formatter: '{value}°C'
        },
        min: 0,
        max: 40
      },
      series: [
        {
          name: '最高温度',
          data: weekWeatherList.value.map(item => item.tempMax),  // 最高温度
          type: 'line',
          smooth: true,
          itemStyle: { color: '#ff4d4f' },
          lineStyle: { width: 2 },
          label: {
            show: true,
            position: 'top',
            formatter: '{c}°C'
          }
        },
        {
          name: '最低温度',
          data: weekWeatherList.value.map(item => item.tempMin), // 最低温度
          type: 'line',
          smooth: true,
          itemStyle: { color: '#409EFF' },
          lineStyle: { width: 2 },
          label: {
            show: true,
            position: 'bottom',
            formatter: '{c}°C'
          }
        }
      ],
      grid: {
        left: '3%',
        right: '3%',
        bottom: '10%',
        top: '20%',
        containLabel: true
      }
    }
    myChart2.setOption(option)
  }

  // 初始化图表实例
  const initCharts = () => {
    if (!chartRef.value || !chartRef2.value) {
      setTimeout(initCharts, 100)
      return
    }

    if (myChart) myChart.dispose()
    if (myChart2) myChart2.dispose()

    myChart = echarts.init(chartRef.value)
    myChart2 = echarts.init(chartRef2.value)

    initChart()
    initWeeklyChart()
  }

  // 每小时更新数据
  const setupHourlyUpdate = () => {
    const now = new Date()
    const delay = (60 - now.getMinutes()) * 60 * 1000 - now.getSeconds() * 1000

    setTimeout(() => {
      currentHour.value = new Date().getHours()
      initChart()
      timer = setInterval(() => {
        currentHour.value = new Date().getHours()
        initChart()
      }, 3600 * 1000)
    }, delay)
  }

  // 窗口resize处理
  const handleResize = () => {
    myChart?.resize()
    myChart2?.resize()
  }

  onMounted(() => {
    initCharts()
    window.addEventListener('resize', handleResize)
    setupHourlyUpdate()
  })

  onBeforeUnmount(() => {
    window.removeEventListener('resize', handleResize)
    clearInterval(timer)
    myChart?.dispose()
    myChart2?.dispose()
  })

  // 深度监听数据变化
  watch(() => props.hourWeather, () => {
    nextTick(() => {
      initChart()
    })
  }, { deep: true })

  watch(() => props.weekWeather, () => {
    nextTick(() => {
      initWeeklyChart()
    })
  }, { deep: true })

  watch(activeName, () => {
    nextTick(() => {
      initChart()
    })
  })

  watch(currentHour, () => {
    nextTick(() => {
      initChart()
    })
  })
</script>

<template>
  <!-- 头部天气信息 -->
  <el-card class="headerCard">
    <div class="header">
      <div class="left">
        <h3>{{ props.detailWeather.city || props.detailWeather.province }}</h3>
        <div class="weather-info">
          <span>今天：{{ props.detailWeather.weather }}</span>
          <span
            >{{ props.detailWeather.tempMin }}℃-{{
              props.detailWeather.tempMax
            }}℃</span
          >
          <span>{{ props.detailWeather.windDirection }}</span>
        </div>
      </div>
      <div class="right">
        <div class="date-info">
          <span>{{ dateInfo.gregorianDate }}</span>
          <span>{{ dateInfo.weekDay }}</span>
          <span>{{ dateInfo.lunarDate }}</span>
        </div>
      </div>
    </div>
    <div class="temperature">
      <strong>{{ props.detailWeather.currentTemp }}°</strong>
      <div class="weather-detail">
        <span>{{ props.detailWeather.weather }}</span>
        <span>{{ props.detailWeather.windDirection }}风</span>
        <span>{{ props.detailWeather.windScale }}级</span>
      </div>
    </div>
    <div class="sunup">
      <span>湿度{{ props.detailWeather.humidity }} %</span>
      <span class="time-item">
        <el-icon size="27" color="#F7B500">
          <Sunrise />
        </el-icon>
        {{ props.detailWeather.sunriseTime }}
      </span>
      <span class="time-item">
        <el-icon size="20" color="#FF7D00">
          <Sunset />
        </el-icon>
        {{ props.detailWeather.sunsetTime }}
      </span>
    </div>
  </el-card>
  <!-- 24小时天气表 -->
  <el-card>
    <div class="chart-container">
      <div
        ref="chartRef"
        class="chart"
        style="width: 100%; height: 400px"
      ></div>
      <el-tabs v-model="activeName" type="card" class="chart-tabs">
        <el-tab-pane label="温度" name="temperature"></el-tab-pane>
        <el-tab-pane label="风力方向" name="wind"></el-tab-pane>
        <el-tab-pane label="空气质量" name="airQuality"></el-tab-pane>
      </el-tabs>
    </div>
  </el-card>
  <!-- 周天气 -->
  <el-card class="centerCard">
    <h3 class="weekTitle">未来一周天气预报</h3>
    <div class="weekWeather">
      <ul>
        <li v-for="(item, index) in weekWeatherList" :key="index">
          <div class="top">
            <span>{{ item.weekday }}</span>
            <span>{{ item.forecastDate }}</span>
            <span>
              <el-icon :size="30" :style="{ color: item.color }">
                <component :is="item.icon" theme="outline" />
              </el-icon>
            </span>
          </div>
          <div class="bottom">
            <p>
              <el-icon :size="18" :style="{ color: '#85C1E9' }">
                <Promotion />
              </el-icon>
              {{ item.windScale }}级
            </p>
            <span class="air" :style="{ backgroundColor: item.aqColor }">{{
              item.aq
            }}</span>
          </div>
        </li>
      </ul>
      <div ref="chartRef2" class="chart2"></div>
    </div>
  </el-card>
</template>

<style scoped>
  .headerCard {
    margin: 10px 0 5px 0;
  }
  /* 基础布局 */
  .header {
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
    line-height: 1;
  }

  /* 左侧区域 */
  .left {
    display: flex;
    align-items: flex-end;
    gap: 20px; /* 城市名和天气信息的间距 */
  }

  h3 {
    font-size: 23px;
    margin: 0;
  }

  /* 天气信息（今日） */
  .weather-info {
    display: inline-flex;
    gap: 12px; /* 控制"小雨/温度/风力"间距 */
    align-items: center;
  }

  /* 右侧日期 */
  .date-info {
    display: inline-flex;
    gap: 10px; /* 控制日期各部分间距 */
  }

  /* 温度大数字区域 */
  .temperature {
    display: flex;
    align-items: flex-end;
    gap: 20px; /* "26°"和天气详情的间距 */
    margin: 40px 0 20px;
  }

  .temperature strong {
    font-size: 50px;
  }

  /* 天气详情（多云/东北风/3级） */
  .weather-detail {
    display: inline-flex;
    gap: 10px; /* 控制天气描述词间距 */
    padding-bottom: 5px; /* 微调垂直对齐 */
  }

  /* 温度区域样式 */
  .temperature {
    margin: 40px 0 20px;
    gap: 20px; /* 统一使用 gap 替代 margin-left */
  }

  .temperature strong {
    font-size: 50px;
  }

  /* 移除冗余的 span 样式 */
  .header .left span,
  .header .right span,
  .temperature span {
    margin: 0; /* 清除所有 margin，统一使用 gap */
  }
  .sunup {
    display: flex;
    align-items: center;
    gap: 16px; /* 控制子元素间距 */
    font-size: 14px;
  }

  .time-item {
    display: flex;
    align-items: center;
    gap: 8px; /* 图标和文字间距 */
  }
  /* 图表容器 */
  .chart-container {
    position: relative;
    margin: 30px 0;
  }

  /* 图表 */
  .chart {
    width: 100%;
    height: 300px;
  }

  /* 选项卡样式 */
  .chart-tabs {
    position: absolute;
    top: 0;
    right: 0;
    z-index: 10;
    width: 300px;
  }

  /* 调整选项卡间距 */
  :deep(.el-tabs__item) {
    padding: 0 15px;
  }
  .centerCard {
    margin: 5px 0;
  }

  /* 周天气 */
  .weekTitle {
    margin-bottom: 30px;
    font-size: 20px;
  }
  .weekWeather {
    position: relative;
  }
  .weekWeather ul {
    display: flex;
    margin: 0 60px;
    height: 300px;
  }
  .weekWeather ul li {
    display: flex;
    padding: 10px 0;
    width: 150px;
    flex-direction: column;
    justify-content: space-between;
    /* background-color: #fafafa; */
    border-right: 1px solid #f5f5f5;
  }
  .weekWeather ul li:first-child {
    border-left: 1px solid #f5f5f5;
  }
  .weekWeather ul li:nth-child(2){
    background-color: #F0F8FF;
  }
  .weekWeather ul li .top {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: center;
    height: 90px;
  }
  .weekWeather ul li .bottom {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: center;
    height: 60px;
  }
  .weekWeather ul li .bottom .air {
    padding: 0 10px;
    text-align: center;
    /* width: 40px; */
    background-color: #40c057;
    border-radius: 15px;
    color: #fff;
  }
  .chart2 {
    position: absolute;
    width: 1108px;
    height: 200px;
    top: 70px;
    left: 25px;
  }
</style>
